package com.hj.system.system.shiro;

import com.hj.system.base.config.ApplicationContextRegister;
import com.hj.system.base.utils.ShiroUtils;
import com.hj.system.system.dao.UserDao;
import com.hj.system.system.dao.UserFingerDao;
import com.hj.system.system.domain.UserDO;
import com.hj.system.system.domain.UserFingerDO;
import com.hj.system.system.service.MenuService;
import com.hj.system.system.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        String userId = ShiroUtils.getUserId();
        MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
        Set<String> perms = menuService.listPerms(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        RoleService roleService = ApplicationContextRegister.getBean(RoleService.class);
        Set<String> roles = roleService.listUserRoleIds(userId);
        info.setRoles(roles);
        info.setStringPermissions(perms);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UserNameLoginToken userNameLoginToken = (UserNameLoginToken) token;
        String username = (String) userNameLoginToken.getPrincipal();
        Map<String, Object> map = new HashMap<>(1);
        map.put("username", username);
        UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
        // 查询用户信息
        UserDO user = userMapper.get(map);
        // 账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        }
        // 账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        if (userNameLoginToken.isRequriedPassword()) {
            String password = new String((char[]) userNameLoginToken.getCredentials());
            // 密码错误
            if (!password.equals(user.getPassword())) {
                throw new IncorrectCredentialsException("密码不正确");
            }
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        return info;
    }

}
